package com.ruoyi.cms.tag.service.impl;

import com.ruoyi.cms.post.mapper.CmsPostTagMapper;
import com.ruoyi.cms.tag.domain.CmsTag;
import com.ruoyi.cms.tag.mapper.CmsTagMapper;
import com.ruoyi.cms.tag.service.ICmsTagService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author toumakazusa
 * @since 1.0.0
 */
@Service
public class CmsTagServiceImpl implements ICmsTagService {
    @Autowired
    private CmsTagMapper cmsTagMapper;

    @Autowired
    private CmsPostTagMapper cmsPostTagMapper;

    @Override
    public List<CmsTag> selectCmsTagList(CmsTag cmsTag) {
        List<CmsTag> cmsTagList = cmsTagMapper.selectCmsTagList(cmsTag);
        if (cmsTagList != null && cmsTagList.size() > 0) {
            for (CmsTag tag : cmsTagList) {
                int postNum = cmsPostTagMapper.countPostByTagId(tag.getTagId());
                tag.setPostNum(postNum);
            }
        }
        return cmsTagList;
    }

    @Override
    public CmsTag selectCmsTagByTagId(Long tagId) {
        return cmsTagMapper.selectCmsTagByTagId(tagId);
    }

    @Override
    public int insertCmsTag(CmsTag cmsTag) {
        List<CmsTag> cmsTagList = cmsTagMapper.selectCmsTagListByTagName(cmsTag.getTagName());
        if (cmsTagList.size() > 0) {
            throw new ServiceException("标签名称已存在");
        }
        cmsTag.setCreateTime(DateUtils.getNowDate());
        return cmsTagMapper.insertCmsTag(cmsTag);
    }

    @Override
    public int updateCmsTag(CmsTag cmsTag) {
        List<CmsTag> cmsTagList = cmsTagMapper.selectCmsTagListByTagName(cmsTag.getTagName());
        if (cmsTagList.size() > 0) {
            for (CmsTag tag : cmsTagList) {
                if (!cmsTag.getTagId().equals(tag.getTagId())) {
                    throw new ServiceException("标签名称已存在");
                }
            }
        }
        cmsTag.setUpdateTime(DateUtils.getNowDate());
        return cmsTagMapper.updateCmsTag(cmsTag);
    }

    @Override
    public int deleteCmsTagByTagIds(Long[] tagIds) {
        for (Long tagId : tagIds) {
            //删除标签帖子关联表信息
            cmsPostTagMapper.deletePostTagByTagId(tagId);
        }
        return cmsTagMapper.deleteCmsTagByTagIds(tagIds);
    }
}
